﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Http;
using Telerik.Web.UI;

namespace RadAutoCompleteBoxWebAPIHighlight
{
    // Author: Otto Neff | webapps-in-action.com
    public class DataController : ApiController
    {
        [HttpPost]
        public AutoCompleteBoxData Search(dynamic data)
        {
            dynamic context = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(data["context"].ToString());
            List<AutoCompleteBoxItemData> results = new List<AutoCompleteBoxItemData>();
            try
            {
                string searchFor = context["Text"].ToString();
                string customParameter = context["CustomParameter"].ToString();
                if (searchFor.Length < 2)
                {
                    return new AutoCompleteBoxData { Items = results.ToArray() };
                }
                string[] searchTerms = searchFor.Split(' ');
                foreach (DataRow dummyData in GetDummyData().Tables["DummyData"].AsEnumerable())
                {
                    Dictionary<string, object> metaData = new Dictionary<string, object>();
                    metaData.Add("LOGO_URL", "/" + dummyData["Image"]);
                    bool allFound = true;
                    string searchText = " ";
                    searchText = Convert.ToString(dummyData.ItemArray[1] + " " + dummyData.ItemArray[2] + " " + dummyData.ItemArray[3] + " " + dummyData.ItemArray[4]);
                    foreach (string searchValue in searchTerms)
                    {
                        if (searchText.ToLower().Contains(searchValue.ToLower())) { }
                        else
                        {
                            allFound = false;
                        }
                    }
                    if (allFound)
                    {
                        string largeText = dummyData["Name"].ToString() + " " + dummyData["Id"].ToString();
                        string smallText = dummyData["Drinks"].ToString() + " " + dummyData["Drives"].ToString();
                        metaData.Add("RESULT_HTML", "<b>" + HighlightKeywords(string.Join(",", searchTerms), largeText) + "</b><br/><span class='smallResultText'>" + HighlightKeywords(string.Join(",", searchTerms), smallText) + "<br/>" + customParameter + "</span>");
                        results.Add(new AutoCompleteBoxItemData { Text = dummyData["Id"].ToString() + " " + dummyData["Name"].ToString(), Value = dummyData["Guid"].ToString(), Attributes = metaData });
                    }
                }
                return new AutoCompleteBoxData
                {
                    Items = results.ToArray()
                };
            }
            catch (Exception ex) // YOU MIGHT LOG EXCEPTIONS ;-)
            {
                return new AutoCompleteBoxData
                {
                    Items = results.ToArray()
                };
            }
        }
        /// <summary>
        /// GET DUMMY DATA
        /// </summary>
        /// <returns>Carefully. Returns James Bond.</returns>
        private DataSet GetDummyData()
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable("DummyData");
            dt.Columns.Add("Guid");
            dt.Columns.Add("Name");
            dt.Columns.Add("Id");
            dt.Columns.Add("Drinks");
            dt.Columns.Add("Drives");
            dt.Columns.Add("Created");
            dt.Columns.Add("SomeDecimal");
            dt.Columns.Add("Image");
            for (int i = 0; i < 15; i++)
            {
                dt.Rows.Add(new object[] { Guid.NewGuid(), "James Bond", i, "Vodka Martini, shaken not stirred", "Aston Martin DB5", DateTime.Now, 1.50, "bond.jpg" });
                dt.Rows.Add(new object[] { Guid.NewGuid(), "Dr. No", i, "Blood", "Laser Rocket", DateTime.Now, 5.50, "no.jpg" });
            }
            ds.Tables.Add(dt);
            return ds;
        }
        private static string HighlightKeywords(string keywords, string text)
        {
            try
            {
                Regex r = new Regex(@", ?");
                keywords = "(" + r.Replace(keywords, @"|") + ")";
                r = new Regex(keywords, RegexOptions.Singleline | RegexOptions.IgnoreCase);
                return r.Replace(text, new MatchEvaluator(MatchEval));
            }
            catch
            {
                return text;
            }
        }
        private static string MatchEval(Match match)
        {
            if (match.Groups[1].Success)
            {
                return "<b style='color:red;'>" + match.ToString() + "</b>";
            }
            return "";
        }
    }
}






